package com.test.web.config;

import cn.hutool.json.JSONUtil;
import com.he.web.annotation.NeedToken;
import com.he.web.ex.NoAuthException;
import com.he.web.ex.OptionsException;
import com.he.web.util.Jwt;
import com.he.web.util.Webs;
import com.test.web.entity.Backuser;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author heyanjing
 * date:2020-07-03 2020/7/3:11:10
 */
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        log.info("{} {} {} {}", "preHandle", httpServletRequest.getRequestURL(), httpServletRequest.getMethod(), object);
        if (Webs.isOption(httpServletRequest)) {
            // return true;
            throw new OptionsException("options 请求");
        }
        if (object instanceof HandlerMethod) {
            String token = httpServletRequest.getHeader(Webs.TOKEN_KEY);
            HandlerMethod handlerMethod = (HandlerMethod) object;
            Object bean = handlerMethod.getBean();
            //类上的注解标明不需要token校验
            NeedToken classAnnotation = bean.getClass().getAnnotation(NeedToken.class);
            if (classAnnotation != null && !classAnnotation.value()) {
                return true;
            }

            //方法的注解标明不需要token校验
            NeedToken methodAnnotation = handlerMethod.getMethodAnnotation(NeedToken.class);
            if (methodAnnotation != null && !methodAnnotation.value()) {
                return true;
            }
            if (StringUtils.isBlank(token)) {
                throw new NoAuthException("token为空");
            }
            try {
                Claims claims = Jwt.parseJWT(token);
                String subject = claims.getSubject();
                Backuser backuser = JSONUtil.toBean(subject, Backuser.class);
                // 设置token信息
                httpServletRequest.setAttribute(Webs.TOKEN_INFO_KEY, backuser);
            } catch (Exception e) {
                throw new NoAuthException("token转换失败");
            }
        }
        //
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // log.warn("{}", "postHandle");

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        // log.warn("{}", "afterCompletion");
    }

}